package com.wl.user.login.biz.impl;

import com.wl.user.login.biz.VerificationCodeBiz;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeBizImpl implements VerificationCodeBiz {
    private static final int MAX_RETRIES = 3;

    private final JavaMailSender mailSender;
    private final RedisTemplate<String, String> redisTemplate;

    // 验证码有效期5分钟
    private static final long CODE_EXPIRE_TIME = 5 * 60;

    public VerificationCodeBizImpl(JavaMailSender mailSender, RedisTemplate<String, String> redisTemplate) {
        this.mailSender = mailSender;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 生成并发送验证码
     */
    public void sendVerificationCode(String email) throws MessagingException {
        // 生成6位随机数字验证码
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));

        // 存储验证码到Redis，有效期5分钟
        redisTemplate.opsForValue().set(
                "verification_code:" + email,
                code,
                CODE_EXPIRE_TIME,
                TimeUnit.SECONDS
        );

        // 发送邮件
        sendVerificationEmail(email, code);
    }

    /**
     * 发送验证码邮件
     */
    public void sendVerificationEmail(String to, String code) throws MessagingException {
        int attempt = 0;
        while (attempt < MAX_RETRIES) {
            attempt++;
            try {
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

                helper.setFrom("643559709@qq.com");
                helper.setTo(to);
                helper.setSubject("您的验证码");

                String content = "<div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>" +
                        "<h2 style='color: #333;'>感谢您使用我们的服务</h2>" +
                        "<p>您的验证码是：<strong style='font-size: 24px; color: #1890ff;'>" + code + "</strong></p>" +
                        "<p style='color: #999;'>请在5分钟内使用此验证码完成验证，过期失效。</p>" +
                        "<hr style='border: none; border-top: 1px solid #eee;'>" +
                        "<p style='color: #999; font-size: 12px;'>此为系统邮件，请勿回复。</p>" +
                        "</div>";

                helper.setText(content, true);

                // 发送邮件
                mailSender.send(message);
                return; // 发送成功则退出

            } catch (MailSendException e) {
                if (attempt == MAX_RETRIES) {
                    System.out.println(e.getMessage()); //邮件发送失败，已达最大重试次数: {}
                    throw e;
                }
                System.out.println(attempt);//邮件发送失败，正在进行第{}次重试...

                // 指数退避等待
                try {
                    Thread.sleep(1000 * attempt);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new MessagingException("邮件发送被中断", ie);
                }
            }
        }
    }
    /**
     * 验证验证码是否正确
     */
    public boolean verifyCode(String email, String code) {
        try {
            String redisKey = "verification_code:" + email;
            System.out.println("Redis Key: " + redisKey); // 打印完整的Redis key

            String storedCode = redisTemplate.opsForValue().get(redisKey);

            // 添加调试日志
            System.out.println("验证码验证 - 邮箱: " + email);
            System.out.println("输入验证码: " + code);
            System.out.println("存储验证码: " + storedCode);

            if (storedCode == null) {
                System.out.println("验证码不存在或已过期");
                return false;
            }

            // 验证成功后删除验证码（防止重复使用）
            // 在比较前去除空格
            boolean isValid = code != null && code.trim().equals(storedCode.trim());
            System.out.println(isValid);
            if (isValid) {
                redisTemplate.delete(redisKey);
            }

            return isValid;
        } catch (Exception e) {
            System.err.println("验证码验证出错: " + e.getMessage());
            return false;
        }
    }
}